import { getMenuByRouter } from '@/lib/util'
import { routes, routerMap } from '@/router/router'

const state = {
  routers: routes,
  hasGetRole: false
}

const getters = {
  menuList: (state, getters, rootState) => getMenuByRouter(routerMap, rootState.user.access)
}

const mutations = {
  CONACT_ROUTES (state, routerList) {
    state.routers = routerList.concat(routes)
    state.hasGetRole = true
  }
}

// const getAccessRoutersList = (routes, menuList) => {
//   return routes.filter(item => {
//     if (menuList[item.name]) {
//       if (item.children) item.children = getAccessRoutersList(item.children, menuList)
//       return true
//     } else return false
//   })
// }

const getAccessRoutersList = (routes, menuList) => {
  const routesChild = routes[0].children
  const childRoutes = routesChild.filter(item => {
    if (menuList[item.name]) {
      if (item.children) item.children = getChildrenRoutersList(item.children, menuList)
      return true
    } else return false
  })
  routes[0].children = childRoutes
  return routes
}

const getChildrenRoutersList = (childRoutes, menuList) => {
  return childRoutes.filter(item => {
    if (menuList[item.name]) {
      if (item.children) item.children = getChildrenRoutersList(item.children, menuList)
      return true
    } else return false
  })
}

const actions = {
  concatRoutes ({ commit }, menuList) {
    return new Promise((resolve, reject) => {
      try {
        let routerList = []
        if (Object.entries(menuList).every(item => item[1])) {
          routerList = routerMap
        } else {
          routerList = getAccessRoutersList(routerMap, menuList)
        }
        commit('CONACT_ROUTES', routerList)
        resolve(routerList)
        // console.log(routerList)
      } catch (err) {
        reject(err)
      }
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
